package com.gin.no_gay_alliance.manager;

import android.content.Context;
import android.content.DialogInterface;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.NonNull;

import com.gin.nga.callback.JsonCallback;
import com.gin.nga.client.NgaClient;
import com.gin.nga.exception.NgaException;
import com.gin.nga.method.NukeApi;
import com.gin.nga.params.nuke.favor.FavorAddParam;
import com.gin.nga.params.nuke.favor.FavorDelParam;
import com.gin.nga.params.nuke.favor.FavorFolderListParam;
import com.gin.nga.response.body.BaseMessageBody;
import com.gin.nga.response.body.FavorFolderBody;
import com.gin.nga.response.field.FavorFolder;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.callback.Bundle;
import com.gin.no_gay_alliance.callback.Callback;
import com.gin.no_gay_alliance.utils.AlertDialogUtils;
import com.gin.no_gay_alliance.utils.MyHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import okhttp3.Call;

/**
 * 收藏管理器
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/6 10:49
 **/
public class FavorManager {
    /**
     * 收藏夹缓存
     */
    private final HashMap<String, Bundle<List<FavorFolder>>> cache = new HashMap<>();


    /**
     * 主题移除收藏
     *
     * @param param    参数
     * @param callback 回调
     */
    public void topicDel(FavorDelParam param, Callback<BaseMessageBody> callback) {
        NukeApi.favorTopicDel(MyApplication.getClient(), param).async(new JsonCallback<BaseMessageBody>() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                super.onFailure(call, e);
                if (callback != null) {
                    callback.onFailure(call, e);
                }
            }

            @Override
            public void onSuccess(BaseMessageBody body) {
                // 清空缓存
                cache.clear();
                if (callback != null) {
                    callback.onSuccess(body);
                }
            }

            @Override
            public void handleException(NgaException e) {
                super.handleException(e);
                if (callback != null) {
                    callback.handleException(e);
                }
            }
        });
    }

    /**
     * 主题添加收藏弹窗
     *
     * @param context  上下文
     * @param handler  handler
     * @param topicId  主题id
     * @param replyId  回复id
     * @param callback 回调
     */
    public void topicAddDialog(Context context, MyHandler handler, long topicId, long replyId, Callback<BaseMessageBody> callback) {
        favorFolderList(false, data -> handler.post(() -> {
            // 单选框组
            RadioGroup radioGroup = new RadioGroup(context);
            // 添加单选按钮
            for (int i = 0; i < data.size(); i++) {
                FavorFolder folder = data.get(i);
                RadioButton radioButton = new RadioButton(context);
                // 默认选中第一个
                if (i == 0) {
                    radioButton.setChecked(true);
                }
                radioButton.setId(Math.toIntExact(folder.getId()));
                radioButton.setText(String.format(Locale.CHINA, "%s [%s] (%d)", folder.getName(), folder.getType().value, folder.getLength()));
                radioGroup.addView(radioButton);
            }

            AlertDialogUtils.showConfirm(context, "选择收藏夹", "注: 同一主题内对多个回复的收藏会相互覆盖", radioGroup, (d, which) -> {
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    // 请求参数
                    FavorAddParam param = new FavorAddParam(radioGroup.getCheckedRadioButtonId(), topicId, replyId);
                    // 执行添加请求
                    MyApplication.app.managerFactory.getFavorManager().topicAdd(param, callback);
                }
            });
        }));
    }


    /**
     * 主题添加收藏
     *
     * @param param    参数
     * @param callback 回调
     */
    public void topicAdd(FavorAddParam param, Callback<BaseMessageBody> callback) {
        NukeApi.favorTopicAdd(MyApplication.getClient(), param).async(new JsonCallback<BaseMessageBody>() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                super.onFailure(call, e);
                if (callback != null) {
                    callback.onFailure(call, e);
                }
            }

            @Override
            public void onSuccess(BaseMessageBody body) {
                // 清空缓存
                cache.clear();
                if (callback != null) {
                    callback.onSuccess(body);
                }
            }

            @Override
            public void handleException(NgaException e) {
                super.handleException(e);
                if (callback != null) {
                    callback.handleException(e);
                }
            }
        });
    }

    /**
     * 查询收藏夹列表
     *
     * @param ignoreCache 是否忽略缓存
     * @param callback    回调
     */
    public void favorFolderList(boolean ignoreCache, Callback<List<FavorFolder>> callback) {
        favorFolderList(ignoreCache, MyApplication.getClient().getUserId(), callback);
    }

    /**
     * 查询收藏夹列表
     *
     * @param ignoreCache 是否忽略缓存
     * @param callback    回调
     * @param userId
     */
    public void favorFolderList(boolean ignoreCache, long userId, Callback<List<FavorFolder>> callback) {
        favorFolderList(ignoreCache, new FavorFolderListParam(1, userId), callback);
    }

    /**
     * 查询收藏夹列表
     *
     * @param ignoreCache 是否忽略缓存
     * @param param       参数
     * @param callback    回调
     */
    public void favorFolderList(boolean ignoreCache, FavorFolderListParam param, Callback<List<FavorFolder>> callback) {
        // 客户端
        NgaClient client = MyApplication.getClient();
        // 缓存key
        String key = String.format(Locale.CHINA,
                "%s_%d_%d",
                FavorFolderListParam.class.getSimpleName(),
                param.getUserId(),
                param.getPage());
        if (Bundle.checkCache(ignoreCache, cache, key, callback)) {
            return;
        }
        callback.beforeRequest();
        // 执行请求
        NukeApi.favorFolderList(client, param).async(new JsonCallback<FavorFolderBody>() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                callback.onFailure(call, e);
            }

            @Override
            public void onSuccess(FavorFolderBody body) {
                cache.put(key, new Bundle<>(body.getData()));
                callback.onSuccess(body.getData());
            }

            @Override
            public void handleException(NgaException e) {
                callback.handleException(e);
            }
        });
    }
}
